import React, { useEffect, useState } from 'react';
import {
  Container,
  Box,
  CircularProgress,
  Typography,
  Breadcrumbs,
  Link,
} from '@mui/material';
import { useParams, Link as RouterLink } from 'react-router-dom';
import { Implementation } from '../types';
import { api } from '../services/api';
import ImplementationDetail from '../components/CodeImplementation/ImplementationDetail';

const ImplementationDetailPage: React.FC = () => {
  const { implementationId } = useParams<{ implementationId: string }>();
  const [implementation, setImplementation] = useState<Implementation | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadImplementation = async () => {
      if (!implementationId) return;

      setLoading(true);
      try {
        const data = await api.getImplementationById(implementationId);
        setImplementation(data);
      } catch (error) {
        console.error('Error loading implementation:', error);
      } finally {
        setLoading(false);
      }
    };

    loadImplementation();
  }, [implementationId]);

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '60vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (!implementation) {
    return (
      <Container>
        <Typography variant="h5" color="error">
          实现不存在
        </Typography>
      </Container>
    );
  }

  return (
    <Container>
      {/* 面包屑导航 */}
      <Breadcrumbs sx={{ my: 2 }}>
        <Link component={RouterLink} to="/" color="inherit">
          首页
        </Link>
        <Link
          component={RouterLink}
          to={`/category/${implementation.category.main}`}
          color="inherit"
        >
          {implementation.category.main}
        </Link>
        <Link
          component={RouterLink}
          to={`/category/${implementation.category.sub}`}
          color="inherit"
        >
          {implementation.category.sub}
        </Link>
        <Typography color="text.primary">{implementation.title}</Typography>
      </Breadcrumbs>

      {/* 实现详情 */}
      <ImplementationDetail implementation={implementation} />
    </Container>
  );
};

export default ImplementationDetailPage;
